<template>
	<a-select v-model:value="trainCode" :filterOption="filterTrainCodeOption" :style="'width: ' + localWidth"
	          allowClear
	          placeholder="请选择车次"
	          show-search
	          @change="onChange">
		<a-select-option v-for="item in trainList" :key="item.code" :label="item.code + item.start + item.end"
		                 :value="item.code">
			{{ item.code }} | {{ item.start }} ~ {{ item.end }}
		</a-select-option>
	</a-select>
</template>

<script>
import {defineComponent, onMounted, ref, watch} from 'vue';
import axios from 'axios';
import {notification} from 'ant-design-vue';

export default defineComponent({
	name: 'train-select-view',
	props: ['modelValue', 'width'],
	emits: ['update:modelValue', 'change'],
	setup(props, {emit}){
		/**
		 * 车次编号
		 */
		const trainCode = ref();
		/**
		 * 车次列表
		 */
		const trainList = ref([]);
		/**
		 * 接收父组件的宽度
		 */
		const localWidth = ref(props.width);
		// 如果父组件未传，则默认100%
		if(Tool.isEmpty(props.width)){
			localWidth.value = '100%';
		}

		// 利用watch，动态获取父组件的值，如果放在onMounted或其它方法里，则只有第一次有效
		watch(() => props.modelValue, () => {
			trainCode.value = props.modelValue;
		}, {immediate: true});

		/**
		 * 查询车次列表
		 */
		const selectTrainList = () => {
			axios.get('/business/admin/train/select-list').then((r) => {
				const {success, message, content} = r.data;
				if(success){
					trainList.value = content;
				}else{
					notification.error({message: message});
				}
			});
		};

		/**
		 * 车次下拉框筛选
		 */
		const filterTrainCodeOption = (input, option) => {
			return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
		};

		/**
		 * 将当前组件的值响应给父组件
		 */
		const onChange = (value) => {
			emit('update:modelValue', value);
			let train = trainList.value.filter(item => item.code === value)[0];
			if(Tool.isEmpty(train)){
				train = {};
			}
			emit('change', train);
		};

		/**
		 * 页面加载完调用
		 */
		onMounted(() => {
			selectTrainList();
		});

		return {
			trainCode,
			trainList,
			filterTrainCodeOption,
			onChange,
			localWidth
		};
	},
});
</script>